﻿using ESMAM.Model.SYS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;


namespace ESMAM.Web.Core.Filters
{

    /// <summary>
    /// 检验登陆和权限的filter
    /// </summary>
    [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
    public class AuthorityFilter : AuthorizeAttribute
    {
        /// <summary>
        /// 检查用户登录
        /// </summary>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var sessionUser = HttpContext.Current.Session[BaseController.CONST_SESSION_USER];
            if (sessionUser == null || !(sessionUser is sys_user))//验证Session中存储的用户，当前不存在，则表示 未登陆
            {
                //验证当前请求是否是Ajax请求，非Ajax请求则跳转到登陆页面
                if (filterContext.RequestContext.HttpContext.Request.Url.PathAndQuery == "/" || !filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Login", action = "Index" }));
                }
                else//Ajax请求的方式，一般情况下是，当前用户已经登陆过，但是Session超时，需要 弹窗提示，重新登陆
                {
                    filterContext.Result = ControllerExt.JsonBJUI((Controller)filterContext.Controller, 301, "会话超时，需重新登陆！");
                }
            }
        }
    }

}